<template>
  <a-card :bordered="false">
    <div class="ma-content-block lg:flex justify-between">
      <div ref="crudContentRef" class="lg:w-2/12 w-full h-full pr-2">
        <a-list :max-height="divHeight" :loading="loading" :scrollbar="true" size="small">
          <template #header>
            <div class="flex justify-between items-center" :style="{ height: '30px' }">
              <span>用戶分組</span>
              <a-tooltip content="添加分組">
                <a-button shape="round" size="small" @click="openAddPopup" type="primary">
                  <template #icon><icon-plus /></template>
                </a-button>
              </a-tooltip>
            </div>
          </template>
          <a-list-item v-for="(item, index) in data" :key="item.id">
            <div class="w-full flex justify-between items-center">
              <a-button class="w-full" :type="title == item.name ? 'outline' : ''" @click="getUserGroup(item)">
                {{ item.name }}({{ item.user_count }})
              </a-button>
              <a-popconfirm content="確定刪除嗎？" @before-ok="del(item)" type="warning">
                <a-link>
                  <template #icon>
                    <icon-delete />
                  </template>
                </a-link>
              </a-popconfirm>
            </div>
          </a-list-item>
        </a-list>
        <div class="mt-2 text-right" v-if="data.length > 0">
          <a-pagination
            :total="pageObj.total"
            :page-size-options="[20]"
            @page-size-change="pageSizeChangeHandler"
            @change="pageChangeHandler"
            v-model:current="pageObj.page"
            :page-size="pageObj.pageSize"
            style="display: inline-flex" />
        </div>
      </div>
      <div class="lg:w-10/12 w-full">
        <a-card :title="title + ' 分組'" :loading="loading" :header-style="{ height: '45px' }">
          <div class="pl-2 pr-4">
            <a-form ref="formRef" size="small" :model="formData2" :auto-label-width="true">
              <a-form-item label="分組名稱" field="name">
                <a-input v-model="formData2.name" placeholder="請輸入分組名稱" />
              </a-form-item>
              <a-form-item label="描述" field="description">
                <a-input v-model="formData2.description" placeholder="請輸入描述" />
              </a-form-item>
              <a-form-item v-if="title.length > 0">
                <a-button type="primary" @click="submit1">保存修改</a-button>
              </a-form-item>
            </a-form>
            <a-divider :margin="12" />
            <a-button type="primary" style="margin: 0 8px 8px 0" @click="openAddUserPopup"> 新增 </a-button>
            <a-button @click="removeUserToGroup"> 批量刪除 </a-button>
            <a-table
              :row-selection="rowSelection"
              v-model:selectedKeys="selectedKeys"
              row-key="uid"
              :columns="columns"
              :data="clickItem.members || []">
            </a-table>
          </div>
        </a-card>
      </div>
      <a-modal
        v-model:visible="visible"
        title="添加分組"
        width="600px"
        :ok-loading="btnLoading"
        @cancel="close"
        @before-ok="submit">
        <a-form ref="formRef" :model="formData" :rules="rules" :auto-label-width="true">
          <a-form-item label="分組名稱" field="name">
            <a-input v-model="formData.name" placeholder="請輸入分組名稱" />
          </a-form-item>
          <a-form-item label="描述" field="description">
            <a-input v-model="formData.description" placeholder="請輸入描述" />
          </a-form-item>
        </a-form>
      </a-modal>
      <a-modal
        v-model:visible="visible2"
        title="添加用戶到分組"
        width="60%"
        :ok-loading="btnLoading2"
        @cancel="close2"
        @before-ok="submit2">
        <a-input
          class="mb-2 mr-2 w-5"
          style="width: 150px; margin-right: 12px; margin-bottom: 12px"
          v-model="keyword"
          allow-clear
          @clear="openAddUserPopup(1)"
          placeholder="請輸入關鍵詞" />
        <a-button size="small" @click="openAddUserPopup(1)" type="primary"> <icon-search /> 搜索 </a-button>
        <a-table
          :loading="loading2"
          :row-selection="rowSelection"
          v-model:selectedKeys="selectedKeys2"
          row-key="uid"
          :scroll="{
            y: '500px',
          }"
          class="min-h-[300px]"
          :pagination="false"
          :columns="columns2"
          :data="userList || []">
        </a-table>
        <a-pagination
          :total="pageObj2.total"
          show-page-size
          :page-size-options="[10, 20, 30, 50, 100]"
          @page-size-change="pageSizeChangeHandler2"
          @change="pageChangeHandler2"
          v-model:current="pageObj2.page"
          :page-size="pageObj2.pageSize"
          class="mt-4"
          style="display: inline-flex" />
      </a-modal>
    </div>
  </a-card>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { Message } from '@arco-design/web-vue'
import { useUserStore } from '@/store'
import userGroupApi from '@/api/userGroup'
const userStore = useUserStore()
const rowSelection = {
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: true,
}
const selectedKeys = ref([])
const columns = [
  {
    title: '暱稱',
    dataIndex: 'nickname',
  },
  {
    title: '聯絡電話',
    dataIndex: 'phone',
  },
  {
    title: '信箱',
    dataIndex: 'email',
  },
  {
    title: '審核狀態',
    dataIndex: 'statusDesc',
    align: 'center',
    width: 100,
  },
  {
    title: '註冊時間',
    dataIndex: 'sign_up_time',
    slotName: 'sign_up_time',
    width: 170,
  },
  {
    title: '加入分組時間',
    dataIndex: 'join_time',
    slotName: 'join_time',
    width: 170,
  },
]
const columns2 = [
  {
    title: 'UID',
    dataIndex: 'uid',
  },
  {
    title: '暱稱',
    dataIndex: 'game_nickname',
  },
  {
    title: '用戶標籤',
    dataIndex: 'title',
  },
  {
    title: '創建時間',
    dataIndex: 'create_time',
    slotName: 'create_time',
    width: 170,
  },
]
const userUidMap = ref({})
const userList = ref([])
const selectedKeys2 = ref([])
const visible2 = ref(false)
const keyword = ref('')
const btnLoading2 = ref(false)
const loading2 = ref(false)
const openAddUserPopup = async (page = 1) => {
  loading2.value = true
  try {
    const res = await userGroupApi.getUserInfoList({
      page,
      page_size: pageObj2.pageSize,
      keyword: keyword.value,
    })
    pageObj2.total = res.data.total
    pageObj2.page = res.data.current_page
    pageObj2.pageSize = res.data.page_size
    loading2.value = false
    visible2.value = true
    res.data.items.forEach((item) => {
      if (userUidMap.value[item.uid]) {
        item.disabled = true
      } else {
        item.disabled = false
      }
    })
    userList.value = res.data.items
  } catch (error) {
    loading2.value = false
  }
}
const pageSizeChangeHandler2 = async (pageSize) => {
  pageObj2.page = 1
  pageObj2.pageSize = pageSize
  openAddUserPopup()
}
const pageChangeHandler2 = async (currentPage) => {
  pageObj2.page = currentPage
  openAddUserPopup(currentPage)
}
const close2 = async () => {
  visible2.value = false
  btnLoading2.value = false
  keyword.value = ''
  selectedKeys2.value = []
}
const submit2 = async (done) => {
  try {
    await userGroupApi.addUserToGroup(clickItem.value.id, {
      uids: selectedKeys2.value,
    })
    Message.success(`添加成功！`)
    getUserGroup(clickItem.value)
    close2()
  } catch (error) {
    btnLoading.value = false
    done(false)
  }
}
const title = ref('')
const pageObj = reactive({
  page: 1,
  pageSize: 20,
  total: 0,
})
const pageObj2 = reactive({
  page: 1,
  pageSize: 10,
  total: 0,
})
const rules = reactive({
  name: [{ required: true, message: '請輸入分組名稱' }],
  description: [{ required: true, message: '請輸入描述' }],
})
const visible = ref(false)
const btnLoading = ref(false)
const formRef = ref(null)
const clickItem = ref({})

const del = async (record) => {
  try {
    await userGroupApi.deleteUserGroup(record.id)
    Message.success(`刪除成功！`)
    init()
  } catch (error) {
    return false
  }
}
const getUserGroup = async (record) => {
  loading.value = true
  userUidMap.value = {}
  try {
    const res = await userGroupApi.getUserGroup(record.id)
    selectedKeys.value = []
    title.value = res.data.name
    formData2.value.name = res.data.name
    formData2.value.description = res.data.description
    clickItem.value = res.data
    res.data.members.forEach((item) => {
      userUidMap.value[item.uid] = item
    })
    data.value.forEach((item) => {
      if (item.id == res.data.id) {
        item.name = res.data.name
        item.description = res.data.description
        item.user_count = res.data.members.length
      }
    })
    loading.value = false
  } catch (error) {
    loading.value = false
  }
}

const formData2 = ref({
  name: '',
  description: '',
})
const formData = ref({
  name: '',
  description: '',
})

const removeUserToGroup = async () => {
  if (selectedKeys.value.length === 0) {
    Message.error('請選擇要操作的紀錄')
    return
  }
  loading.value = true
  try {
    await userGroupApi.removeUserToGroup(clickItem.value.id, {
      uids: selectedKeys.value,
    })
    Message.success('操作成功')
    loading.value = false
    getUserGroup(clickItem.value)
  } catch (error) {
    loading.value = false
  }
}

const openAddPopup = () => {
  formData.value = {
    name: '',
    description: '',
  }
  visible.value = true
}
const close = () => {
  visible.value = false
  btnLoading.value = false
  formRef.value?.resetFields()
}
const submit1 = async () => {
  if (!formData2.value.name) {
    return Message.error('請輸入分組名稱')
  }
  if (!formData2.value.description) {
    return Message.error('請輸入描述')
  }
  loading.value = true
  try {
    await userGroupApi.updateUserGroup(clickItem.value.id, {
      name: formData2.value.name,
      description: formData2.value.description,
    })

    Message.success(`修改成功！`)
    loading.value = false
    getUserGroup(clickItem.value)
  } catch (error) {
    loading.value = false
  }
}

const submit = async (done) => {
  const validate = await formRef.value?.validate()
  if (validate) return done(false)
  try {
    await userGroupApi.createUserGroup(formData.value)
    close()
    Message.success(`添加成功！`)
    init()
  } catch (error) {
    btnLoading.value = false
    done(false)
  }
}
const data = ref([])

const pageSizeChangeHandler = async (pageSize) => {
  pageObj.page = 1
  pageObj.pageSize = pageSize
  init()
}
const pageChangeHandler = async (currentPage) => {
  pageObj.page = currentPage
  init(currentPage)
}
const loading = ref(false)

const init = async (page = 1) => {
  loading.value = true
  try {
    const res = await userGroupApi.getUserGroupList({
      page,
      page_size: pageObj.pageSize,
    })
    pageObj.total = res.data.total
    pageObj.page = res.data.current_page
    pageObj.pageSize = res.data.page_size
    data.value = res.data.items
    loading.value = false
    if (res.data.items.length > 0) {
      getUserGroup(res.data.items[0])
    } else {
      title.value = ''
      formData2.value.name = ''
      formData2.value.description = ''
    }
  } catch (error) {
    loading.value = false
  }
}
init()

const crudContentRef = ref()
onMounted(async () => {
  await nextTick(() => {
    window.addEventListener('resize', settingFixedPage, false)
    settingFixedPage()
  })
})
const divHeight = ref(650)
const settingFixedPage = () => {
  const workAreaHeight = document.querySelector('.work-area').offsetHeight
  const arcoListContent = document.querySelector('.arco-list-content')
  let tableHeight = workAreaHeight - 24 - 32 - 8 - 2
  arcoListContent.style.height = tableHeight - 76 + 'px'
  divHeight.value = tableHeight
  if (crudContentRef.value) {
    crudContentRef.value.style.height = tableHeight + 'px'
  }
}
</script>
